<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of TypeCommon
 *
 * @author Administrator
 */
class TypeService {

    function findTypeById($id) {
        return D('type')->find($id);
    }

    function listTypeNameByIds($typeIds, $field = '*') {
        $typeTable = D('type');
        $where['id'] = array('in', $typeIds);

        return $typeTable->where($where)->field($field)->select();
    }

    function getTypeIdByName($name) {
        $typeTable = D('type');
        $type = $typeTable->where(array('name' => $name))->find();
        if (!is_null($type)) {
            return $type['id'];
        }
        return $typeTable->data(array('name' => $name))->add();
    }

    function getTypeIdByNames($names) {
        $typeTable = D('type');
        $map['name'] = array('in', $names);
        $types = $typeTable->where($map)->select();


        if (count($names) == count($types)) {
            $idList = array();
            foreach ($types as $type) {
                array_push($idList, $type['id']);
            }
            return $idList;
        }
        $searchNames = array();
        foreach ($types as $type) {
            array_push($searchNames, $type['name']);
        }

        $ot = array_diff($names, $searchNames);

        $data = array();
        foreach ($ot as $o) {
            if (!empty($o)) {
                array_push($data, array('name' => $o));
            }
        }
        $typeTable->addAll($data);

        return $this->getTypeIdByNames($names);
    }

    /**
     * 所有的二级类型
     */
    function listChildTypes() {
        $where['name'] = array('exp', 'is not null');
        $where['root'] = array('exp', 'is null');
        return D('type')->where($where)->select();
    }

    /**
     * 所有顶级类型
     */
    function listRootTypes() {
        $where['root'] = array('eq', 1);
        return D('type')->where($where)->select();
    }

    /**
     * 类型更换
     * @param type $rootType 顶级类型
     * @param type $childTypes 二级类型集合
     */
    function updateType($rootTypeId, $childTypeIds) {
        $typeModel = new Model(); // 实例化一个model对象 没有对应任何数据表
        $typeModel->startTrans();
        $childId = array();
        $lastId = $typeModel->execute("update type set type_id = " . $rootTypeId . " where id in(" . $childTypeIds . ")");

        $typeModel->commit();

        return $lastId;
    }

    /**
     * 当前顶级类型下的二级类型
     * @param type $rootTypeId 
     */
    function listChildTypesByRootTypeId($rootTypeId) {
        $where['type_id'] = array('eq', $rootTypeId);
        $where['name'] = array('exp', 'is not null');
        $list = D('type')->where($where)->select();

        return $list;
    }

}

?>
